<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.upup.fun","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="关于异步编程的听课笔记。">
<meta property="og:type" content="article">
<meta property="og:title" content="异步编程的回调解决方案">
<meta property="og:url" content="http://blog.upup.fun/2019/06/22/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E5%9B%9E%E8%B0%83%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/index.html">
<meta property="og:site_name" content="猫头猫">
<meta property="og:description" content="关于异步编程的听课笔记。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-06-22T08:04:03.000Z">
<meta property="article:modified_time" content="2020-04-17T08:55:24.070Z">
<meta property="article:author" content="猫头猫">
<meta property="article:tag" content="js">
<meta property="article:tag" content="语法">
<meta property="article:tag" content="听课笔记">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://blog.upup.fun/2019/06/22/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E5%9B%9E%E8%B0%83%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>异步编程的回调解决方案 | 猫头猫</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">猫头猫</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-works">

    <a href="/works/" rel="section"><i class="fa fa-smile fa-fw"></i>小作品</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.upup.fun/2019/06/22/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E5%9B%9E%E8%B0%83%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="猫头猫">
      <meta itemprop="description" content="如果我是一只小猫咪，每天只要喵喵叫。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="猫头猫">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          异步编程的回调解决方案
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-06-22 16:04:03" itemprop="dateCreated datePublished" datetime="2019-06-22T16:04:03+08:00">2019-06-22</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>758</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>1 分钟</span>
            </span>
            <div class="post-description">关于异步编程的听课笔记。</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><strong>异步编程是面试时一定会问的</strong></p>
<hr>
<ol>
<li>传统异步编程方案</li>
<li>promise</li>
</ol>
<hr>
<h3 id="传统异步编程的解决方案"><a href="#传统异步编程的解决方案" class="headerlink" title="传统异步编程的解决方案"></a>传统异步编程的解决方案</h3><p>js：事件驱动机制，单线程，异步操作实现阻塞IO</p>
<h4 id="callback回调函数："><a href="#callback回调函数：" class="headerlink" title="callback回调函数："></a>callback回调函数：</h4><p>通过参数传入回调，回调时让函数的调用者判断发生了什么。<br>缺点：不利于代码的阅读和回复，程序的流程会比较乱，而且每个任务只能指定一个回调函数。</p>
<h4 id="观察者模式（事件发布-订阅模式）："><a href="#观察者模式（事件发布-订阅模式）：" class="headerlink" title="观察者模式（事件发布/订阅模式）："></a>观察者模式（事件发布/订阅模式）：</h4><p>思想：回调函数的事件化，任务的执行不取决于代码的执行顺序，而取决于某个事件是否发生。</p>
<p>优点：可以绑定多个事件，每个事件可以指定多个回调函数。<br>缺点：程序变成事件驱动型，运行流程不清晰。</p>
<h4 id="deferred延迟函数："><a href="#deferred延迟函数：" class="headerlink" title="deferred延迟函数："></a>deferred延迟函数：</h4><p>通过deferred对象给异步操作进行状态绑定，deferred对象提供统一的API，对异步操作的状态操作。</p>
<p>优点：避免了层层嵌套的回调函数deferred对象提供统一的接口，使得控制异步操作更加容易。（Promise的思想）<br>缺点：状态不可逆，状态一旦确定，无法更改。</p>
<hr>
<h3 id="Promise规范"><a href="#Promise规范" class="headerlink" title="Promise规范"></a>Promise规范</h3><p>Promise是异步编程的一种解决方案，简单来说是一个容器，里面保存着一个异步操作的结果。提供统一的API，各种异步操作都可以使用同样的方法进行处理。</p>
<blockquote>
<p>参考资料：阮一峰es6教程</p>
</blockquote>
<p>经典的数据类型的判断方法：toString.call(),是什么类型，得到的字符串就是[object 类型名]；使用typeof不准确。</p>
<p>Promise， Deferred就是一些容器的语法糖，剩下的就是封装语法糖。</p>
<p>原理：是一个容器，内部封装着一些callbacks，而这个容器有两个方法：add和fire，add用来向容器中添加callback，fire则用来实现依次调用容器内所有的callback。容器有着一些参数，比如once，memory和stopOnFalse。promise和deferred则是这个容器的一些语法糖。</p>

    </div>

    
    
    
        <div class="reward-container">
  <div>嘻嘻</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="猫头猫 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="猫头猫 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/images/wechat_channel.jpg">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
              <a href="/tags/%E8%AF%AD%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> 语法</a>
              <a href="/tags/%E5%90%AC%E8%AF%BE%E7%AC%94%E8%AE%B0/" rel="tag"><i class="fa fa-tag"></i> 听课笔记</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/06/21/es5-apply-call-bind-%E7%BD%91%E6%98%93%E4%BA%91%E8%AF%BE%E5%A0%82%E5%90%AC%E8%AF%BE%E7%AC%94%E8%AE%B0/" rel="prev" title="es5 apply call bind-网易云课堂听课笔记">
      <i class="fa fa-chevron-left"></i> es5 apply call bind-网易云课堂听课笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/06/25/%E4%B8%80%E4%BA%9B%E6%AF%94%E8%BE%83%E6%9C%89%E8%B6%A3%E7%9A%84JS%E9%A2%98/" rel="next" title="一些比较有趣的JS题">
      一些比较有趣的JS题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=477844082&auto=1&height=66"></iframe>

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%A0%E7%BB%9F%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="nav-number">1.</span> <span class="nav-text">传统异步编程的解决方案</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#callback%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="nav-number">1.1.</span> <span class="nav-text">callback回调函数：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88%E4%BA%8B%E4%BB%B6%E5%8F%91%E5%B8%83-%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F%EF%BC%89%EF%BC%9A"><span class="nav-number">1.2.</span> <span class="nav-text">观察者模式（事件发布&#x2F;订阅模式）：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#deferred%E5%BB%B6%E8%BF%9F%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="nav-number">1.3.</span> <span class="nav-text">deferred延迟函数：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Promise%E8%A7%84%E8%8C%83"><span class="nav-number">2.</span> <span class="nav-text">Promise规范</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="猫头猫"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">猫头猫</p>
  <div class="site-description" itemprop="description">如果我是一只小猫咪，每天只要喵喵叫。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/maotoumao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;maotoumao" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:lhx_xjtu@163.com" title="E-Mail → mailto:lhx_xjtu@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">猫头猫</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">91k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:22</span>
   | <a href="http://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备20005224号-2 </a>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
